package com.jr.controller;

import com.jr.pojo.User;
import com.jr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/info")
    @ResponseBody
    public Map<String, Object> getUserInfo(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.getUserByUsername(username);
            if (user != null) {
                result.put("success", true);
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("message", "用户不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户名是否已存在
            if (userService.getUserByUsername(user.getUsername()) != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }
            
            // 检查邮箱是否已存在
            if (userService.getUserByEmail(user.getEmail()) != null) {
                result.put("success", false);
                result.put("message", "邮箱已存在");
                return result;
            }
            
            // 验证用户类型
            if (user.getUserType() == null || user.getUserType().trim().isEmpty()) {
                user.setUserType("pet_owner"); // 默认为宠物主人
            }
            
            // 调用Service层插入用户
            boolean insertSuccess = userService.insertUser(user);
            if (insertSuccess) {
                result.put("success", true);
                result.put("message", "注册成功");
                
                // 返回用户信息（不包含密码）
                User registeredUser = userService.getUserByUsername(user.getUsername());
                if (registeredUser != null) {
                    registeredUser.setPassword(null); // 不返回密码
                    result.put("user", registeredUser);
                }
            } else {
                result.put("success", false);
                result.put("message", "注册失败，请稍后重试");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
        }
        return result;
    }

    // 登录功能已移至ProgramController处理

    @GetMapping("/{userId}")
    @ResponseBody
    public Map<String, Object> getUserById(@PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.getUserById(userId);
            if (user != null) {
                result.put("success", true);
                result.put("data", user);
            } else {
                result.put("success", false);
                result.put("message", "用户不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        return result;
    }

    @PutMapping("/update")
    @ResponseBody
    public Map<String, Object> updateUser(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userService.updateUser(user);
            if (success) {
                result.put("success", true);
                result.put("message", "更新成功");
            } else {
                result.put("success", false);
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    @PutMapping("/password")
    @ResponseBody
    public Map<String, Object> updatePassword(@RequestParam Integer userId, @RequestParam String newPassword) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userService.updatePassword(userId, newPassword);
            if (success) {
                result.put("success", true);
                result.put("message", "密码更新成功");
            } else {
                result.put("success", false);
                result.put("message", "密码更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "密码更新失败：" + e.getMessage());
        }
        return result;
    }

    @GetMapping("/type/{userType}")
    @ResponseBody
    public Map<String, Object> getUsersByType(@PathVariable String userType) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<User> users = userService.getUsersByType(userType);
            result.put("success", true);
            result.put("data", users);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        return result;
    }

    @DeleteMapping("/{userId}")
    @ResponseBody
    public Map<String, Object> deleteUser(@PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userService.deleteUser(userId);
            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    @PostMapping("/updatePassword")
    @ResponseBody
    public Map<String, Object> updatePassword(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) request.get("userId");
            String newPassword = (String) request.get("password");
            
            if (userId == null || newPassword == null || newPassword.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "参数不完整");
                return result;
            }
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }
            
            // 更新密码（Service层会自动加密）
            user.setPassword(newPassword);
            boolean updateSuccess = userService.insertUser(user); // 重新插入会更新密码
            
            if (updateSuccess) {
                result.put("success", true);
                result.put("message", "密码更新成功");
            } else {
                result.put("success", false);
                result.put("message", "密码更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
        }
        return result;
    }
}
